/**
 * Created by 游永年 on 2019-01-13 16:28.
 * 测试题组件,有听力题和测试题
 * 这里改成一大题的一组小题,回答用
 */

import {Flex, Radio, WingBlank} from "antd-mobile";
import {connect} from 'dva';
import React, {Component} from 'react';
import style from './TestQuiz.less';

class Answer extends Component {
  render() {
    const {timus, myAnswer} = this.props;
    return (
      <div className={style.wrap}>
        {timus.map((timu, index) => {
          const {question = '', tmOptionList = [], id} = timu;
          const {stuAnswer = ''} = myAnswer.find(({timuId}) => timuId === id) || {};
          return <div key={id + ''}>
            <WingBlank>
              {index + 1}、{question}
              <OneAnswer answer={stuAnswer} options={tmOptionList}
                         onChange={a => this.select({xtIndex: index, timuId: id, answer: a})}/>
            </WingBlank>
          </div>;
        })}
      </div>
    );
  }

  select = ({xtIndex, answer, timuId}) => this.props.dispatch({type: 'quiz/answer', answer, xtIndex, timuId});
}

Answer.propTypes = {};

const opts = ({quiz}) => {
  const {quizList, currIndex = 0, myAnswer = []} = quiz || {};
  //取当前大题
  const dati = quizList[currIndex] || {};
  const {timus = []} = dati;

  return {
    timus,
    myAnswer,
  };
};

export default connect(opts)(Answer);

/**
 * 一组大题的一个小题
 *
 */
class OneAnswer extends Component {
  render() {
    const {options, answer} = this.props;
    return (
      <div className={style.wrap}>
        <Flex style={{padding: '15px'}} direction={'column'} align={'start'}>
          {options.map(({content, id, optionType}) => {
            const optionLetter = whichOption(optionType)
            return <Flex.Item style={{marginBottom: '15px'}} key={id + ''}>
              <Radio checked={optionLetter === answer}
                     onChange={_ => this.onSelect(optionLetter)}>{optionLetter}、{content}
              </Radio>
            </Flex.Item>
          })
          }
        </Flex>
      </div>
    );
  }

  onSelect = (answer) => {
    const {onChange} = this.props;
    onChange(answer);
  };
}

/**
 * 由contentType转成ABCD
 */
const optionsMap = new Map([
  ['1', 'A'],
  ['2', 'B'],
  ['3', 'C'],
  ['4', 'D'],
]);
const whichOption = (val = '0') => optionsMap.get(val + '');
